package com.urea.system.service.impl;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.google.common.collect.Maps;
import com.urea.common.core.domain.entity.Customer;
import com.urea.common.exception.ServiceException;
import com.urea.common.utils.SecurityUtils;
import com.urea.system.domain.Order;
import com.urea.system.domain.Terminal;
import com.urea.system.service.ICustomerService;
import com.urea.system.service.IOrderService;
import com.urea.system.service.ITerminalService;
import com.urea.system.service.IWxMpService;
import lombok.extern.slf4j.Slf4j;
import me.chanjar.weixin.common.bean.WxOAuth2UserInfo;
import me.chanjar.weixin.common.bean.oauth2.WxOAuth2AccessToken;
import me.chanjar.weixin.common.error.WxErrorException;
import me.chanjar.weixin.mp.api.WxMpService;
import me.chanjar.weixin.mp.bean.template.WxMpTemplateData;
import me.chanjar.weixin.mp.bean.template.WxMpTemplateMessage;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Map;
import java.util.Objects;

/**
 * 类描述:
 *
 * @author fangXu
 * @version 1.0
 * @date 2023/9/12 15:10
 */
@Service
@Slf4j
public class WxMpServiceImpl implements IWxMpService {

    @Autowired
    private WxMpService mpService;
    @Autowired
    private ITerminalService terminalService;
    @Autowired
    private IOrderService orderService;
    @Autowired
    private ICustomerService customerService;


    @Override
    public String getAccessToken() {
        try {
            return mpService.getAccessToken();
        } catch (WxErrorException e) {
            log.info("##########获取公众号accessToken失败:{}###########", e.getMessage());
            throw new RuntimeException(e);
        }
    }

    /**
     * 公众号数据统计获取订单数据 终端数量
     *
     * @return 结果
     */
    @Override
    public Map<String, Long> getStatistics() {
        Map<String, Long> map = Maps.newHashMap();
        // 终端数量
        long tCount = terminalService.count(Wrappers.lambdaQuery(Terminal.class).eq(Terminal::getAgentUid, SecurityUtils.getUserId()));
        // 订单数量
        long oCount = orderService.count(Wrappers.lambdaQuery(Order.class).eq(Order::getAgentId, SecurityUtils.getUserId()));
        map.put("terminalCount", tCount);
        map.put("orderCount", oCount);
        return map;
    }

    /**
     * 发送模板消息
     *
     * @param msgMap     消息内容
     * @param phone      接收用户
     * @param templateId 消息模板id
     */
    @Override
    public void sendTemplateMsg(Map<String, String> msgMap, String phone, String templateId) {
        // 手机号获取用户信息
        log.info("##############准备发送模板消息:{}给用户:{}################",templateId,phone);
        Customer customer = customerService.getOne(Wrappers.lambdaQuery(Customer.class).eq(Customer::getPhone, phone));
        if (Objects.isNull(customer)) {
            throw new ServiceException("用户信息异常");
        }
        WxMpTemplateMessage templateMessage = WxMpTemplateMessage.builder()
                .toUser(customer.getOpenId())
                .templateId(templateId)
                // todo 跳转页面待补充
                .url(null)
                .build();
        for (String s : msgMap.keySet()) {
            templateMessage.addData(new WxMpTemplateData(s, msgMap.get(s)));
        }
        try {
            mpService.getTemplateMsgService().sendTemplateMsg(templateMessage);
        } catch (WxErrorException e) {
            log.info("#########模板消息发送错误:{}##########",e.getMessage());
        }
        log.info("##############发送模板消息:{}给用户:{}成功################",templateId,phone);
    }

    /**
     * 获取用户的openId
     *
     * @param code code
     * @return
     */
    @Override
    public String getOpenId(String code) {
        try {
            WxOAuth2AccessToken wxOAuth2AccessToken = mpService.getOAuth2Service().getAccessToken(code);
            WxOAuth2UserInfo userInfo = mpService.getOAuth2Service().getUserInfo(wxOAuth2AccessToken, "zh_CN");
            return userInfo.getOpenid();
            // todo openId入库
        } catch (WxErrorException e) {
            log.info("获取用户的accessToken失败,错误:{}#################", e.getMessage());
            throw new ServiceException("获取用户的accessToken失败");
        }
    }
}
